package com.joke.locomotive;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.jdbc.mysql.MysqlServerConnect;
import com.joke.util.Const;
import com.joke.util.DateUtil;

public class ImportTxt {
	
	private static String date = DateUtil.formatString(new Date(), "yyyyMM");
	static String writeTxTPath=Const.fabu+date+Const.localTxt;
	
	public static void readTxt(String[] filePaths) {
		BufferedReader reader;
		try {
			Map<String, String> txtMap = new HashMap<String, String>();
			
			for (int i = 0; i < filePaths.length; i++) {
				reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(filePaths[i]))));
				String line = "";
				String content = "";
				while ((line = reader.readLine()) != null) {
					if(!"".equals(line.trim()) &&line.trim().length()<=800  && line.indexOf("匿") == -1
							&& line.trim().indexOf("糗百") == -1 && line.trim().indexOf("??????") == -1
							&& line.trim().indexOf("捧腹") == -1&& line.trim().indexOf("查看全文") == -1) {
						content = line.trim().replace("", "").replace("🙃", "").replace("🙏", "")
								.replace("🐻", "").replace("😂", "").replace("$$", "")
								.replaceAll("[\\ud800\\udc00-\\udbff\\udfff\\ud800-\\udfff]", "");
						txtMap.put(content, "");
					}
				}
				
			}
			System.out.println("全部读取完毕，共"+txtMap.size()+"条段子");
			
			Object[] txt = txtMap.keySet().toArray();
			
			//保存入库段子
			writeTxt(txt);
			//保存数据库  本地和服务器
			MysqlServerConnect.insertTxTLoco(txt);
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
			
	}
	
	/**
	 * 将入库的文本段子做个备份
	 * @param map
	 */
	public static void writeTxt(Object[] txt) {
		
		BufferedWriter out = null;
		try {
			out = new BufferedWriter(new FileWriter(writeTxTPath, true));//追加形式
			for (Object str : txt) {
				out.write(str.toString()+"\r\n");
			}
			System.out.println("写入txt完毕");
		} catch (IOException e) {
			e.printStackTrace();
		}  finally {
			try {
				out.flush();
			} catch (IOException e) {
				e.printStackTrace();
			} // 把缓存区内容压入文件  
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			} // 最后记得关闭文件  
		}
	}
	
	
	public static void main(String[] args) {
		String date = DateUtil.formatString(new Date(), DateUtil.YMD);
		String [] filePaths = new String[2];
		filePaths[0] = "D:\\LocoDown\\fabu\\"+date+"baisiTxT.txt";
		filePaths[1] = "D:\\LocoDown\\fabu\\"+date+"neihanTxT.txt";
		readTxt(filePaths);
	}

}
